package cn.sdormitory.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.sdormitory.basedata.dao.BDormitoryDao;
import cn.sdormitory.basedata.entity.BDevice;
import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.service.BDormitoryService;
import cn.sdormitory.basedata.vo.BDormitoryVO;
import cn.sdormitory.common.constant.CommonConstant;
import cn.sdormitory.mq.RabbitSenderService;
import cn.sdormitory.service.AppManualAttenceService;
import cn.sdormitory.smartdor.dao.SdAttenceDao;
import cn.sdormitory.smartdor.entity.AdManualAttence;
import cn.sdormitory.smartdor.entity.SdAttence;
import cn.sdormitory.smartdor.vo.DormitoryAttenceVo;
import cn.sdormitory.sys.dao.SysConfigDao;
import cn.sdormitory.sys.entity.SysConfig;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @创建人：zhouyang
 * @创建时间：2021/10/27 14:46
 * @version：V1.0
 */
@Service
public class AppManualAttenceServiceImpl extends ServiceImpl<SdAttenceDao, SdAttence> implements AppManualAttenceService {
    @Resource
    private SdAttenceDao sdAttenceDao;
    @Resource
    private BDormitoryDao bDormitoryDao;
    @Resource
    private BDormitoryService bDormitoryService;
    @Resource
    private RabbitSenderService rabbitSenderService;
    @Resource
    private SysConfigDao sysConfigDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<DormitoryAttenceVo> getAppDorAttenceManual(String className, String storey, String accessDate,String buildingNo) {
//        if (new Date().getHours() < CommonConstant.ATTENDANCE_TIME_INT && ("".equals(accessDate) || accessDate == null)) {
//            Calendar cal = Calendar.getInstance();
//            cal.add(Calendar.DATE, -1);
//            Date d = cal.getTime();
//            accessDate=d;
//        }

        //找出重复的学生数据
        List<String> studentNoList = sdAttenceDao.getAllStudentNo(accessDate,buildingNo,storey);
        Set<String> set = new HashSet<>();
        List<String> duplicates = new ArrayList<>();
        for (String str : studentNoList) {
            if (!set.add(str)) {
                duplicates.add(str);
            }
        }
        //去掉list中的重复数据
        List<String> newDuplicates = new ArrayList<>();
        for(String str : duplicates){
            if(!newDuplicates.contains(str)){
                newDuplicates.add(str);
            }
        }
        //查询数据，删除多余数据后插入
        for(String studentNo : newDuplicates){
            List<SdAttence> sdAttenceList = sdAttenceDao.getAttenceByDateAndStudentNo(accessDate, studentNo);
            SdAttence sdAttence = new SdAttence();
            if(sdAttenceList != null && sdAttenceList.size() > 0){
                sdAttence = sdAttenceList.get(0);
                sdAttenceDao.deleteByStuNoAndADate(studentNo,accessDate);
                sdAttenceDao.insert(sdAttence);
            }
        }


        List<DormitoryAttenceVo> list = sdAttenceDao.getAppDorAttenceManual(className, storey, accessDate, buildingNo);
//        List<DormitoryAttenceVo> newList = new ArrayList<>(list.size());
//        list.forEach(item -> {
//            if(newList == null){
//                newList.add(item);
//            }else if(newList.forEach(subItem ->{ subItem.get
//
//            })){}
//        });
        return sdAttenceDao.getAppDorAttenceManual(className,storey,accessDate,buildingNo);
    }

    @Override
    public List<BDormitoryVO> getAppDormitoryList() {
        return bDormitoryDao.getAppDormitoryList();
    }

    public int addManualAttence(AdManualAttence adManualAttence){
        int count = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            String[] studentNoArray = adManualAttence.getStudentNoArray();
            Integer[] statusArray = adManualAttence.getStatusArray();
            BDormitory bDormitory=bDormitoryService.getBDormitoryById(adManualAttence.getDormitoryId());
            if(studentNoArray!=null && studentNoArray.length>0) {
                for (int i = 0; i < studentNoArray.length; i++) {
                    SdAttence sdAttence = new SdAttence();

                    sdAttence.setStudentNo(studentNoArray[i]);
                    sdAttence.setAccessDate(adManualAttence.getAttenceDate());
                    sdAttence.setAttenceStatus(statusArray[i] + "");
                    sdAttence.setBuildingNo(bDormitory.getBuildingNo());
                    sdAttence.setStorey(bDormitory.getStorey());
                    sdAttence.setBdormitoryId(adManualAttence.getDormitoryId());
                    sdAttence.setDormitoryNo(bDormitory.getDormitoryNo());
                    sdAttence.setFlag("1");

                    System.out.println("开始执行查询，考勤时间： "+format.format(sdAttence.getAccessDate())+" 学号： "+sdAttence.getStudentNo());
                    List<SdAttence> attenceList = sdAttenceDao.getAttenceByDateAndStudentNo(format.format(sdAttence.getAccessDate()),sdAttence.getStudentNo());
                    // 根据学号以及考勤时间判断考勤表中是否有存在的记录
                    if(attenceList==null || attenceList.size()<1) {
                        sdAttenceDao.insert(sdAttence);
                    }else{
                        // 根据学号更新考勤状态
                        //System.out.println("------- 开始执行更新考勤信息： 学号： "+sdAttence.getStudentNo()+"考勤时间： "+format.format(sdAttence.getAccessDate()) +"考勤状态： "+sdAttence.getAttenceStatus());
                        sdAttenceDao.updateAttenceStatus(sdAttence.getStudentNo(),format.format(sdAttence.getAccessDate()),sdAttence.getAttenceStatus());
                    }
                }
            }
            count = 1;
        }catch (Exception ex){
            ex.printStackTrace();
            count = 0;
        }

        return  count;
    }

    @Override
    public List<BDormitoryVO> getAppDorListByStorey(String buildingNo, String storey) {
        return bDormitoryDao.getAppDorListByStorey(buildingNo,storey);
    }

    @Override
    public Long getAppDorListByDorNo(String buildingNo, String storey, String dormitoryNo) {
        return bDormitoryDao.getAppDorListByDorNo(buildingNo,storey,dormitoryNo);
    }

//    @Override
//    public List<SdAttence> getSdAttenceByCondition(SdAttence condition) {
//        return sdAttenceDao.getSdAttenceByCondition(condition);
//    }

    @Override
    public List<SdAttence> getSdAttenceExcList(SdAttence query) {
        return sdAttenceDao.getSdAttenceExcList(query);
    }

    @Override
    public int updateStudentSdAttence(SdAttence entity) {
        return sdAttenceDao.updateById(entity);
    }

    @Override
    public int publishSyncSdAttence(SdAttence entity) {
        //查询系统配置中的宿舍考勤时间
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getParamKey,"attendance.dormitory.rules");
        SysConfig sysConfig = sysConfigDao.selectOne(wrapper);
        //查询设备号
        List<BDevice> deviceList = sdAttenceDao.getDeviceNo(entity.getBuildingNo(), entity.getStorey());
        if(deviceList == null || deviceList.size() <= 0){
            return -1;
        }
        List<Map<String,Object>> list = new ArrayList<>();

        String dateStr = DateUtil.today();
        for(BDevice item : deviceList){
            Map<String,Object> map = new HashMap<>();
//            map.put("beginTime", "2023-11-28 22:00:00");
//            map.put("endTime", "2023-11-28 22:15:00");
            map.put("beginTime", dateStr+" " + sysConfig.getParamValue().split("-")[0]+":00");
            map.put("endTime", dateStr+" " + sysConfig.getParamValue().split("-")[1]+":00");
            map.put("deviceNo",item.getSerialNo());
            list.add(map);
        }


        rabbitSenderService.sendMqMessage(JSON.toJSONString(list),null);
        return 1;
    }

    @Override
    public List<SdAttence> getMendCardStuList(SdAttence query) {
        return sdAttenceDao.getMendCardStuList(query);
    }
}
